﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Db;
using System.Data;
using cn.Util;

namespace yq.SyncCaChe
{
    /// <summary>
    /// 删除缓存中和数据库不同步的部分
    /// 只在数据库发生删除或者修改并且没有修改ver版本的号的时候启用
    /// </summary>
    public class MonitorDB
    {

        public bool IsStop = false;

        /// <summary>
        /// 执行间隔
        /// </summary>
        /// <param name="guid">更新服务序号，每个调用请不要重复</param>
        /// <param name="interval"></param>
        public void Open(string guid, int interval = 200)
        {
            IsStop = false;
            while (IsStop == false)
            {
                //开始标记数据 使用事务
                DbHelper dbt = new DbHelper(new DBTrans());
                string updatewhere = WebConfig.IsWinform ? " where Status=0 and IsWebCache<>1 " : " where Status=0 ";
                var updateSql = dbt.GetSqlStringCommond("update  CaChe_UpdateLog set Status=1,mark='" + guid + "'  " + updatewhere);
                dbt.ExecuteNonQuery(updateSql);
                dbt.Commit();


                //查询已标记的数据
                DbHelper db = new DbHelper();
                var selectSql = db.GetSqlStringCommond("SELECT * FROM CaChe_UpdateLog where mark='" + guid + "' ");
                var list = db.ExecuteDataTable(selectSql);
                foreach (DataRow dataRow in list.Rows)
                {
                    ModelUpdate(dataRow);
                }


                //删除已更新的
                DbHelper deletedb = new DbHelper();
                var delete = deletedb.GetSqlStringCommond("delete  FROM CaChe_UpdateLog where Status=1 and mark='" + guid + "' ");
                int count = deletedb.ExecuteNonQuery(delete);
                Console.WriteLine("更新" + count + "条缓存");


                Thread.Sleep(interval);
            }

        }

        /// <summary>
        /// 更新单数据
        /// </summary>
        private void ModelUpdate(DataRow rw)
        {
            string fullName = rw["TableName"].ToString().ExtToModelName();
            string keyValue = rw["KeyValue"].ToString();

            var cacheConfig = yq.CaChe<object>.GetConfigHost(fullName);

            if (cacheConfig.Type == ICache.CaCheType.WebCache && WebConfig.IsWinform)
            {
                DbHelper db = new DbHelper();
                string sql = "update  CaChe_UpdateLog set Status=0,IsWebCache=1,mark=''  ";
                sql += " where TableName='" + rw["TableName"].ToString() + "'";
                var updateSql = db.GetSqlStringCommond(sql);
                db.ExecuteNonQuery(updateSql);
            }
            else
            {
                yq.CaChe<object>.RefreshDelete(fullName, keyValue);
            }
        }


        public void Stop()
        {
            IsStop = true;
        }

    }
}
